/**
 * Copyright 2006 Brad Reynolds
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.leeloo.databinding.internal.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.osgi.framework.Bundle;

/**
 * Reads a snippet (file) from the file system and caches the contents. Single
 * line comments are ignored.
 * 
 * @author Brad Reynolds
 */
public class JavaSnippetLoader {
    private final Bundle bundle;
    private int serverPortNumber;
    
    /**
     * Line separator for the platform.
     */
    public static final String NEW_LINE = System.getProperty("line.separator"); //$NON-NLS-1$
    private static final Pattern SERVER_PORT_NUMBER = Pattern.compile("#\\{server_port_number\\}"); //$NON-NLS-1$

    /**
     * Constructs a new instance.
     * 
     * @param bundle
     * @param serverPortNumber
     */
    public JavaSnippetLoader(Bundle bundle, int serverPortNumber) {
        if (bundle == null) {
            throw new IllegalArgumentException("Parameter bundle was null."); //$NON-NLS-1$
        }

        this.bundle = bundle;
        this.serverPortNumber = serverPortNumber;
    }

    /**
     * Reads the snippet from the file system.
     * 
     * @param snippetPath path to the snippet relative to the root of the bundle
     * @return snippet
     * @throws RuntimeException
     *             if an exception was thrown
     */
    public String load(String snippetPath) {
        InputStream inputStream = null;
        BufferedReader reader = null;

        String result = null;
        try {
            inputStream = FileLocator.openStream(bundle, new Path(snippetPath), false);
            reader = new BufferedReader(new InputStreamReader(inputStream));

            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (!line.startsWith("//")) { //$NON-NLS-1$
                    //using a regex as String will always compile to a regex if done via String.replaceAll(...).
                    line = SERVER_PORT_NUMBER.matcher(line).replaceAll(Integer.toString(serverPortNumber));

                    buffer.append(line).append(NEW_LINE);
                }
            }

            result = buffer.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
}
